package clas.ac.cn.common.advice;


import clas.ac.cn.common.annotation.IgnoreCommonResponse;

import clas.ac.cn.common.vo.BootSpecificWord;
import clas.ac.cn.common.vo.CommonResponse;
import clas.ac.cn.common.vo.StatusEnum;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author zhangzhang
 */
@RestControllerAdvice
@Slf4j
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {


    @Override
    @SuppressWarnings("all")
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {

        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreCommonResponse.class)) {
            return false;
        }
        if (methodParameter.getMethod().isAnnotationPresent(IgnoreCommonResponse.class)) {
            return false;
        }
        if (methodParameter.getDeclaringClass().isAnnotationPresent(RequestMapping.class)) {
            RequestMapping annotation = methodParameter.getDeclaringClass().getAnnotation(RequestMapping.class);
            String[] value = annotation.value();
            if (StringUtils.indexOfAny(BootSpecificWord.BOOT_ERROR_PATH, value) != -1) {
                return false;
            }
        }

        return true;
    }

    @Override
    @SuppressWarnings("all")
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        CommonResponse<Object> commonResponse = new CommonResponse<>(0, "");
        if (o == null) {
            return commonResponse;
        } else if (o instanceof CommonResponse) {
            commonResponse = (CommonResponse) o;
        } else {
            commonResponse.setCode(StatusEnum.TRUE);
            commonResponse.setData(o);
        }


        return commonResponse;
    }
}
